#include "tools/log.h"
#include "tools/klib.h"
#include "comm/cpu_instr.h"
#include "cpu/irq.h"
#include "ipc/mutex.h"

static mutex_t mutex;

#define COM1_PORT   0x3F8   // RS232端口0初始化

void log_init(void)
{
    mutex_init(&mutex);
    outb(COM1_PORT + 1, 0x00);
    outb(COM1_PORT + 3, 0x80);
    outb(COM1_PORT + 0, 0x03);
    outb(COM1_PORT + 1, 0x00);
    outb(COM1_PORT + 3, 0x03);
    outb(COM1_PORT + 2, 0xC7);
    outb(COM1_PORT + 4, 0x0F);
}

void log_printf(const char *format, ...)
{
    char strbuf[128];
    kernel_memset(strbuf, (uint8_t)0, sizeof strbuf);

    va_list args;
    va_start(args, format);
    kernel_vsprintf(strbuf, format, args);
    va_end(args);
    
    //输出过程不能被打断，以免输出内容错乱，需要加锁
    mutex_lock(&mutex);

    char *p = strbuf;
    while (*p != '\0') {
        while (inb(COM1_PORT + 5) & (1 << 6) == 0); //等待串口空闲
        outb(COM1_PORT, *p++);
    }
    outb(COM1_PORT, '\r');
    outb(COM1_PORT, '\n');

    mutex_unlock(&mutex);
}